<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Arr;
use Throwable;

use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        //
        SwooleExitException::class,
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

     /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Throwable $e
     * @return \Illuminate\Http\Response
     */
    public function render($request,Throwable $e)
    {
        // 参数验证错误的异常，我们需要返回 400 的 http code 和一句错误信息
        if ($e instanceof ValidationException) {
            return response(['error' => Arr::first(Arr::collapse($e->errors()))], 400);
        }
        // 用户认证的异常，我们需要返回 401 的 http code 和错误信息
        if ($e instanceof UnauthorizedHttpException) {
            return response($e->getMessage(), 401);
        }
        if ($e instanceof SwooleExitException) {
            //直接调用perpare
            return $e->getResponse()->prepare($request);
        }
        //  // 如果是生产环境则返回500
        // if (!config('app.debug')) {
        //     $this->throwBusinessException(ResponseEnum::SYSTEM_ERROR);
        // }
        // // 请求类型错误异常抛出
        // if ($exception instanceof MethodNotAllowedHttpException) {
        //     $this->throwBusinessException(ResponseEnum::CLIENT_METHOD_HTTP_TYPE_ERROR);
        // }
        // // 参数校验错误异常抛出
        // if ($exception instanceof ValidationException) {
        //     $this->throwBusinessException(ResponseEnum::CLIENT_PARAMETER_ERROR);
        // }
        // // 路由不存在异常抛出
        // if ($exception instanceof NotFoundHttpException) {
        //     $this->throwBusinessException(ResponseEnum::CLIENT_NOT_FOUND_ERROR);
        // }
        // // 自定义错误异常抛出
        // if ($exception instanceof BusinessException) {
        //     return response()->json([
        //         'status'  => 'fail',
        //         'code'    => $exception->getCode(),
        //         'message' => $exception->getMessage(),
        //         'data'    => null,
        //         'error'  => null,
        //     ]);
        // }

        return parent::render($request, $e);
    }
    


}
